<?php
		include_once "../config.inc.php";
		include '../controladores/ControladorUsuarios.php';
		include_once '../controladores/ControladorImagenes.php';
		include_once '../controladores/ControladorAplicaciones.php';
		include_once '../controladores/ControladorSecciones.php';
		include_once '../controladores/ControladorElementos.php';		
		include_once '../clases/application.php';
		include_once '../clases/section.php';
		
		$command = new ControladorUsuarios();
				
		$userId = $_GET["id"];
		$userEmail = $command->obtainUserEmail($userId);
		
			$command = new ControladorImagenes();
		
		$appName = $_POST["app_name"];
		$appDescription = $_POST["app_description"];
		$appVersion = $_POST["app_version"];
		
		
		$targetApplication = ROUTE_APPLICATIONS_USERS.$userEmail."/Applications/".$appName;
		
		$targetApplicationSections = $targetApplication."/sections";
		$targetApplicationImages = $targetApplication."/images";
		
		mkdir($targetApplication);
		mkdir($targetApplicationImages);
		mkdir($targetApplicationSections);
		
		$nameFile = $_FILES['files']["name"];		
		
		for ($i=0; $i < count($nameFile); $i++){			
			$imageName = basename($nameFile[$i]);
			$target = $targetApplicationImages."/".basename($nameFile[$i]);
		}
		
		$tmpLocations = $_FILES['files']["tmp_name"];		
							
		for ($i=0; $i < count($tmpLocations); $i++) 
				$tmpLocation =  $tmpLocations[$i];
				
		if (move_uploaded_file($tmpLocation,$target)) {
				
				$command->createImage($imageName);	
				
				$command = new ControladorImagenes();
				
				$iconId = $command->searchImageId($imageName);
				
				$app = new Application($userId,$iconId,$appName,$appDescription,$appVersion,strval(date("d-m-Y")),strval(date("d-m-Y")));
				
				$command = new ControladorAplicaciones();
	
				$command->createApplication($app);							
	
				$idApp = $command->searchActiveApplication($userId,$appName);
				
				$defSection = new Section($idApp,DEFAULT_SECTION,strval(date("d-m-Y")),strval(date("d-m-Y")));
				
				$command = new ControladorSecciones;
				
				$command->sectionCreate($defSection);
					
				$secId = $command->searchSectionId($idApp,DEFAULT_SECTION);
	
				$command = new ControladorElementos(TEXT_ELEMENT);
	
				$command->createElement(array("sec_id" => $secId,"text_content" => DEFAULT_SECTION_HTML_CONTENT,"element_order" => 1));				
				header("Location:sections_index.php?user_id=".$userId."&app_id=".$idApp);
		}
?>